import json
import os
import time

import xlrd
import xlwt
import yaml


# read_yaml function to read YAML file
def read_yaml(file_path):
    with open(file_path, 'r') as stream:
        try:
            return yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)


# write_yaml function to write YAML file
def write_yaml(file_path, data):
    with open(file_path, 'w+') as outfile:
        try:
            yaml.dump(data, outfile, allow_unicode=True, default_flow_style=False)
        except yaml.YAMLError as exc:
            print(exc)


# clean yaml
def clean_yaml(file_path):
    with open(file_path, 'w') as outfile:
        outfile.truncate()


# write info to execl file
def write_excel(data_title, data):
    # data_title => list
    # data => dict
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    file_path = os.path.join(os.getcwd(), "commons/" + f"车辆信息_{timestamp}.xlsx")
    if os.path.exists(file_path):
        os.remove(file_path)
    workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
    worksheet = workbook.add_sheet('车辆信息', cell_overwrite_ok=True)

    # write title
    if (not data_title) and len(data) > 0:
        data_title = list(data[0].keys())
    elif data_title:
        row = 0
        col = 0
        for title in data_title:
            worksheet.write(row, col, title)
            col += 1

    for bike_data_index in range(len(data)):
        for key, value in data[bike_data_index].items():
            if key in data_title:
                row = bike_data_index + 1
                col = data_title.index(key)
                # print(value)
                if isinstance(value, dict):
                    value = str(value)
                else:
                    value = str(value)
                worksheet.write(row, col, value)
    workbook.save(file_path)
    return file_path


def read_excel(file_path):
    workbook = xlrd.open_workbook(file_path)
    worksheet = workbook.sheet_by_name('车辆信息')
    data = []
    pass


def write_json(file_name, data):
    file_path = os.path.join(os.getcwd(), "datas/" + f"{file_name}.json")
    content = json.dumps(data, ensure_ascii=False, indent=4)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)

